import React from 'react';
import './index.less';
import {base, promptBox, high, toast, formDownload} from 'nc-lightapp-front';
//import formDownload from 'src/hrpub/common/utils/download/download';
import language from '../../language';
import proFetch from 'src/hrpub/common/utils/project-fetch'

const {NCModal, NCButton, NCInput, NCRadio} = base;
const {Transfer} = high;
export default class ImportModal extends React.Component {
    constructor(props) {
        super(props)
        this.state = ({
            uploadResult: '',
            uploadMsg: '',
            btnShow: true,
            file: [],
            fileNameBack: '',
            fileName: '',
            exportFilter: [],
            importMode: '0',
            dataUpload: false,
            targetKeys: [language["hi6007-000320"], language["hi6007-000321"], language["hi6007-000322"]] // 固定要传
        })
    }

    getInitData = () => {
        let postData = {
            pk_org: this.props.orgVal.refpk,
            func_type: 2,
            funCode: '60070employee_ncc'
        };

        return proFetch({
            url: '/nccloud/hrhi/dataio/ExportSelectSheetAction.do',
            body: postData,
        })
            .then((res) => {
                if (res.success) {
                    this.props.modal.show('dataExport');
                    this.setState({
                        exportFilter: res.data.sheetNames.map(item => {
                            return {
                                key: item,
                                title: item,
                            }
                        })
                    })
                }
            });
    }
    importModeChange = (value) => {
        this.setState({
            importMode: value
        })
    }
    closeModal = () => {
        this.props.onClose();
        this.setState({
            uploadResult: '',
            uploadMsg: '',
            file: [],
            btnShow: true,
            fileName: '',
            fileNameBack: '',
            importMode: '0',
        })
    };
    fileChange = (e) => {
        let file = e.target.files[0]
        let fileName = file.name
        this.setState({
            file,
            fileName,
            uploadResult: '',
            uploadMsg: '',
            btnShow: true,
            fileNameBack: '',
        })
    }

    // 上传成功处理函数
    uploadSuccess = (res) => {
        if (res.success && res.data) {
            if (res.data.finishMsg) {
                this.setState({
                    uploadResult: 'success',
                    uploadMsg: res.data.finishMsg,
                    fileNameBack: res.data.filename,
                    btnShow: true
                })
            } else {
                this.setState({
                    uploadResult: 'error',
                    uploadMsg: res.data.failMsg,
                    fileNameBack: res.data.filename,
                    btnShow: true,
                    importMode: '0',
                })
            }
            this.props.getMainTableData();
        } else {
            this.setState({
                uploadResult: 'error',
                uploadMsg: res.error.message,
                btnShow: false,
                importMode: '0',
            })
        }
    };

    gotoUpload = () => {
        // this.uploadForm.submit();
        let param = new FormData();
        param.append('pk_org', this.props.orgVal.refpk)
        param.append('file', this.state.file)
        param.append('funCode', '60070employee_ncc')
        param.append('sheetNames', this.state.targetKeys.join())
        param.append('bl_pass_check', 'true')
        param.append('import_mode', this.state.importMode)
        proFetch({
            url: '/nccloud/hrhi/dataio/ImportDataAction.do',
            body: param,
            headers: {
                'Content-Type': 'multipart/form-data' //设置post文件的请求头
            }
        }).then((res) => {
            if (res.success) {
                this.uploadSuccess(res)
            }
        })

    }
    // 下载导入模版
    downloadTemplate = async () => {
        this.getInitData('download')
    }
    goToDownload = () => {
        let keysMust = [language["hi6007-000320"], language["hi6007-000321"], language["hi6007-000322"]]
        for (let index = 0; index < keysMust.length; index++) {
            const element = keysMust[index];
            if (!this.state.targetKeys.includes(element)) {
                toast({
                    color: 'warning',
                    content: `${language["hi6007-000320"]}, ${language["hi6007-000321"]}, ${language["hi6007-000322"]}${language["hi6007-000340"]}` // 
                })
                return false;
            }
        }

        this.props.modal.close('dataExport');
        return formDownload({
            params: {
                jsonStr: JSON.stringify({
                    pk_org: this.props.orgVal.refpk,
                    sheetNames: this.state.targetKeys.join(),
                    funCode: '60070employee_ncc'
                })
            },
            url: '/nccloud/hrhi/dataio/ExportExcelAction.do',
            enctype: 2,
        });
    };
    // 点击导入按钮执行函数
    importFile = async () => {
        const {file} = this.state
        if (!file) {
            toast({
                color: 'warning',
                content: language["hi6007-000323"] // 请先选择excel文件！
            })
            return false
        }
        let param = new FormData();
        param.append('pk_org', this.props.orgVal.refpk)
        param.append('file', file)
        param.append('funCode', '60070employee_ncc')

        proFetch({
            url: '/nccloud/hrhi/dataio/ImportSelectSheetAction.do',
            body: param,
            headers: {
                'Content-Type': 'multipart/form-data' //设置post文件的请求头
            }
        }).then((res) => {
            if (res.success) {
                if (res.data.sheetNames) {
                    this.setState({
                        exportFilter: res.data.sheetNames.map(item => {
                            return {
                                key: item,
                                title: item,
                            }
                        }),
                        dataUpload: true
                    }, () => {
                        this.props.modal.show('dataUpload');
                    })
                }
            }
        })

    }
    checkFile = () => {
        const {file, importMode} = this.state
        if (importMode === '0') {
            // "人员基本信息", "组织关系", "工作记录"是必选的
            let keysMust = [language["hi6007-000320"], language["hi6007-000321"], language["hi6007-000322"]]
            for (let index = 0; index < keysMust.length; index++) {
                const element = keysMust[index];
                if (!this.state.targetKeys.includes(element)) {
                    toast({
                        color: 'warning',
                        content: `${language["hi6007-000320"]}, ${language["hi6007-000321"]}, ${language["hi6007-000322"]}${language["hi6007-000340"]}`
                    })
                    return false;
                }
            }
        }
        let param = new FormData();
        param.append('pk_org', this.props.orgVal.refpk)
        param.append('import_mode', importMode)
        param.append('file', file)
        param.append('sheetNames', this.state.targetKeys.join())
        param.append('funCode', '60070employee_ncc')
        proFetch({
            url: '/nccloud/hrhi/dataio/ImportCheckAction.do',
            body: param,
            headers: {
                'Content-Type': 'multipart/form-data' //设置post文件的请求头
            }
        }).then((res) => {
            if (res.success) {
                let msgContent = '', beSureBtnName = '';
                if (res.data.failMsg) {
                    msgContent = res.data.failMsg;
                    beSureBtnName = language["hi6007-000324"];
                } else {
                    msgContent = res.data.confirmMsg;
                    beSureBtnName = language["hi6007-000325"];
                }

                promptBox({
                    color: res.data.failMsg ? "warning" : "success",
                    title: language['hi6007-000008'],/* 国际化处理： 提示*/
                    content: msgContent,
                    // 确定
                    beSureBtnName: beSureBtnName,
                    // 取消
                    cancelBtnName: language['hi6007-000005'] || '取消',
                    beSureBtnClick: async () => {
                        if (res.data.failMsg) {
                            return formDownload({
                                params: {
                                    filename: res.data.filename
                                    // jsonStr: JSON.stringify({
                                    //     filename: res.data.filename
                                    // })
                                },
                                url: '/nccloud/hrhi/dataio/ImportDownloadAction.do',
                                enctype: 2,
                            });
                        } else {
                            this.gotoUpload()
                        }
                    },
                    cancelBtnClick: () => {
                        console.log('Cancel');
                    }
                });
                this.props.modal.close('dataUpload');
                this.setState({
                    dataUpload: false
                })
            }
        })

    }
    onTargetKeysChange = (targetKeys) => {
        this.setState({
            targetKeys
        });
    };
    close = (type) => {
        this.props.modal.close(type);
        this.setState({
            targetKeys: [language["hi6007-000320"], language["hi6007-000321"], language["hi6007-000322"]]
        })
    }

    downloadFile = () => {
        const {fileNameBack} = this.state
        return formDownload({
            params: {
                filename: fileNameBack,
                funCode: '60070employee_ncc'
                // jsonStr: JSON.stringify({
                //     filename: fileNameBack
                // })
            },
            url: '/nccloud/hrhi/dataio/ImportDownloadAction.do',
            enctype: 2,
        });
    }

    render() {
        const {
            exportFilter, targetKeys, fileName,
            uploadResult, uploadMsg, btnShow, importMode, dataUpload
        } = this.state;
        const {visible, modal} = this.props
        const {createModal} = modal;
        const selectedDataSet = () => {
            return <div>
                <div style={{display: dataUpload ? 'block' : 'none', paddingLeft: '20px'}}>
                    <div>{language["hi6007-000326"]}</div>
                    {/* 国际化处理： 数据导入方式*/}
                    <NCRadio.NCRadioGroup
                        name="range"
                        selectedValue={importMode}
                        onChange={this.importModeChange}
                    >
                        <NCRadio value="0">{language["hi6007-000327"]}</NCRadio>{/* 国际化处理： 新增*/}
                        <NCRadio value="1">{language["hi6007-000328"]}</NCRadio>{/* 国际化处理： 更新*/}
                        <NCRadio value="2">{language["hi6007-000329"]}</NCRadio>{/* 国际化处理： 覆盖*/}
                    </NCRadio.NCRadioGroup>
                </div>
                <div style={{margin: 20}}>
                    <Transfer
                        showMoveBtn={false}
                        treeType={false}
                        dataSource={exportFilter}
                        titles={[language['hi6007-000086'], language['hi6007-000087']]}/* 国际化处理： 待选信息集,已选信息集*/
                        targetKeys={targetKeys}
                        onTargetKeysChange={this.onTargetKeysChange}
                        // render={item => item.title}
                        lazy={{container: "modal"}}
                    />
                </div>
            </div>
        };
        return (
            <div className="import">
                <NCModal
                    show={visible}
                    onHide={this.closeModal}
                >
                    <NCModal.Header closeButton={true}>
                        <NCModal.Title>{language["hi6007-000330"]}</NCModal.Title>
                    </NCModal.Header>
                    <NCModal.Body>
                        <div className="importBlock">
                            <div className="ibLeft"/>
                            <div className="ibRight">
                                <div className="ibrCon">
                                    {/* 模板下载 */}
                                    <a className="ibrFir"
                                       onClick={this.downloadTemplate}>{language["hi6007-000331"]}</a>
                                    {/* 第一次导入前请下载模版，并按照文件格式要求填充数据 */}
                                    <span className="ibrSec">{language["hi6007-000332"]}</span>
                                </div>
                            </div>
                            <div className="blockLine"/>
                        </div>
                        <div className="importBlock">
                            <div className="ibLeft"/>
                            <div className="ibRight">
                                <div className="ibrConSec">
                                    <span className="ibrsFir">{language["hi6007-000333"] || '数据文件'}</span>
                                    <span
                                        className="ibrsSec">{language["hi6007-000334"] || '点击按钮选择数据文件，点击导入上传该文件'}</span>
                                </div>

                                <div className="ibrConTh">
                                    <div className="filname">{fileName}</div>
                                    {/* 选择文件 */}
                                    <div className="selectFileBtn">{language["hi6007-000335"] || '选择文件'}</div>
                                    <input className="fileIpt" onChange={(e) => this.fileChange(e)} type="file"
                                           accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/>
                                    {/* 导入 */}
                                    <div className="importBtn"
                                         onClick={this.importFile}>{language["hi6007-000330"] || '导入'}</div>
                                </div>
                            </div>
                            <div className="blockLine"/>
                        </div>
                        <div className="importBlock">
                            <div className="ibLeft"/>
                            <div className="ibRight">
                                <div className="uploadCon">
                                    <span className="resultTitle">{language["hi6007-000336"] || '上传结果'}</span>
                                    <If condition={uploadResult === 'success'}>
                                        <span className="upload-success">{language["hi6007-000337"] || '上传完成'}</span>
                                    </If>
                                    <If condition={uploadResult === 'error'}>
                                        <span className="upload-error">{language["hi6007-000338"] || '上传失败'}</span>
                                    </If>
                                </div>
                                <div className="errorMessage">{uploadMsg} </div>
                                <div className='errfilebtn'>
                                    {uploadMsg && btnShow ? <NCButton colors='primary'
                                                                      onClick={this.downloadFile}>{language["hi6007-000339"] || '生成文件下载'}</NCButton> : null}
                                </div>
                            </div>
                        </div>
                    </NCModal.Body>
                </NCModal>
                <div>
                    {
                        createModal('dataExport', {
                            title: language['hi6007-000088'],/* 国际化处理： 选择导出信息集*/
                            content: selectedDataSet.call(this),
                            hasBackDrop: true,
                            size: 'lg',
                            beSureBtnClick: this.goToDownload,
                            cancelBtnClick: () => this.close('dataExport'), //取消按钮事件回调
                            closeModalEve: () => this.close('dataExport'),
                            userControl: true,
                            className: "export-modal"
                        })
                    }
                </div>
                <div>
                    {
                        createModal('dataUpload', {
                            title: language['hi6007-000088'],/* 国际化处理： 选择导出信息集*/
                            content: selectedDataSet.call(this),
                            hasBackDrop: true,
                            size: 'lg',
                            beSureBtnClick: this.checkFile,
                            cancelBtnClick: () => this.close('dataUpload'), //取消按钮事件回调
                            closeModalEve: () => this.close('dataUpload'),
                            userControl: true,
                            className: "export-modal"
                        })
                    }
                </div>
            </div>
        );
    }
}
